package com.myrobot.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Type;

import com.google.gson.Gson;

public class GsonUtil {
	private static String readFileData(String path) {
		File file = new File(path);
		String data = "";
		InputStreamReader read = null;
		BufferedReader bufferedReader = null;
		if (!file.isFile() || !file.exists()) {
			return null;
		}
		try {
			read = new InputStreamReader(new FileInputStream(file));
			bufferedReader = new BufferedReader(read);
			String lineTxt = null;
			while ((lineTxt = bufferedReader.readLine()) != null) {
				data += lineTxt;
			}

		} catch (IOException e) {
			e.printStackTrace();
			data = null;
		} finally {
			if (read != null) {
				try {
					read.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return data;
	}

	private static void writeFileData(String path, String data) {
		OutputStreamWriter osw = null;
		FileOutputStream fos = null;
		if (path != null && data != null) {
			try {
				fos = new FileOutputStream(path);
				osw = new OutputStreamWriter(fos);
				osw.write(data, 0, data.length());
				osw.flush();
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					if (osw != null) {
						osw.close();
					}
					if (fos != null) {
						fos.close();
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		osw = null;
		fos = null;
	}

	public static <T> T jsonToModel(String json, Type typeOfT) {
		Gson gson = new Gson();
		if (json != null) {
			return gson.fromJson(json, typeOfT);
		} else {
			return null;
		}
	}

	public static <T> T FileToModel(String path, Type typeOfT) {
		String json = readFileData(path);
		if (json != null) {
			return jsonToModel(json, typeOfT);
		} else {
			return null;
		}
	}

	public static String modelToJson(Object typeOfT) {
		Gson gson = new Gson();
		return gson.toJson(typeOfT);
	}

	public static void modelToFile(Object typeOfT, String path) {
		String json = modelToJson(typeOfT);
		writeFileData(path, json);
	}
}